import React, { PureComponent } from 'react';
import { PrimaryC, DATA_ENTRY, AdvancedSearch, TableC, ContentPackage } from '@/src/components';
import ModalInst from './Modal';
import { Card } from 'antd';
import { connect, routerRedux } from 'dva';
import style from './index.less';
import 'moment/locale/zh-cn';
import { isZiGuanEvir } from '../../../../utils/commonFunc';
import { formSelectData, getProductName } from '../../../../utils/utils';
@connect(({ personnelManagement, productAGroupM, counterpartyInformationM, userM: user, loading, globalM }) => ({
  personnelManagement,
  productAGroupM,
  counterpartyInformationM,
  user,
  loading: loading.effects['personnelManagement/getBWList'],
  globalM,
}))
export default class CommonList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false, //控制模态框
      columns: [], //table 字段
      dataSource: [], //黑白名单数据
      pageInfo: [], //分页信息
      currentPage: 1, //当前页
      numInPage: 20, //每页数量
      sortedInfo: null, //排序对象

      orderByField: '', //按某列排序
      order: '', //升序降序
      search: {},
      productList: [], //产品组数据
    };
  }

  componentDidMount() {
    const { numInPage, currentPage } = this.state;
    const { type } = this.props;
    //获取产品组数据 用处理表格的产品组 名称
    this.props.dispatch({
      type: 'productAGroupM/getProductGroups',
      payload: {},
      callback: (e) => {
        this.setState({
          productList: e.groupsList, // 列表下拉数据
          columns: this.state.columns ? [...this.state.columns] : [],
        });
      },
    });
    const {
      globalM: {
        dataDictionary: { COUNTERPARTY_AVAILABLE_STATUS_DICT = [] },
      },
    } = this.props;
    //状态
    this.props.dispatch({
      type: 'personnelManagement/save',
      payload: {
        statusEnum: formSelectData(COUNTERPARTY_AVAILABLE_STATUS_DICT),
      },
    });
    //短名
    this.props.dispatch({
      type: 'personnelManagement/getShortName',
      payload: {},
    });

    //列表数据
    this.props.dispatch({
      type: 'personnelManagement/getBWList',
      payload: {
        numInPage: numInPage,
        currentPage,
        type: type,
      },
      callback: (data) => {
        data.dataSource.map((item, key) => {
          item.key = key;
        });
        this.setState({
          columns: data.columns,
          dataSource: data.dataSource,
          pageInfo: data.pageInfo,
        });
      },
    });
  }

  //点击重置按钮
  onClear = (e) => {
    this.setState({
      search: {},
    });
  };

  //点击查询按钮刷新数据
  getTableData = (e) => {
    const { dispatch, type } = this.props;
    const { numInPage } = this.state;
    this.setState({
      currentPage: 1,
      search: e,
    });
    const value = {
      numInPage: numInPage,
      currentPage: 1,
      type: type,
      ...e,
    };

    dispatch({
      type: 'personnelManagement/getBWList',
      payload: {
        ...value,
      },
      callback: (data) => {
        this.setState({
          dataSource: [],
        });
        data.dataSource.map((item, key) => {
          item.key = key;
        });
        this.setState({
          columns: data.columns,
          dataSource: data.dataSource,
          pageInfo: data.pageInfo,
        });
      },
    });
  };

  //删除后刷新数据
  getTableDataNew = () => {
    const { dispatch, type } = this.props;
    const { numInPage, search } = this.state;

    this.setState({
      currentPage: 1,
    });

    const value = {
      numInPage: numInPage,
      currentPage: 1,
      type: type,
      ...search,
    };

    dispatch({
      type: 'personnelManagement/getBWList',
      payload: {
        ...value,
      },
      callback: (data) => {
        this.setState({
          dataSource: [],
        });
        data.dataSource.map((item, key) => {
          item.key = key;
        });
        this.setState({
          columns: data.columns,
          dataSource: data.dataSource,
          pageInfo: data.pageInfo,
        });
      },
    });
  };

  //分页切换
  handleTableChange3 = (pagination, filter, sorter) => {
    const { dispatch } = this.props;
    const { type } = this.props;
    const { current, pageSize } = pagination;
    const { field, order } = sorter;

    let newOrder = '';
    sorter.order == 'descend' ? (newOrder = 'DESC') : sorter.order == 'ascend' ? (newOrder = 'ASC') : (newOrder = '');

    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        sortedInfo: sorter,
        // dataSource:[]
      },
      () => {
        if (sorter && (sorter.field == 'operation' || sorter.field == 'portfolioName')) return;
        dispatch({
          type: 'personnelManagement/getBWList',
          payload: {
            numInPage: pageSize,
            currentPage: current,
            type: type,
            orderByField: sorter.field || '',
            order: newOrder || '',
            ...this.state.search,
          },
          callback: (data) => {
            this.setState({
              dataSource: [],
            });
            this.setState({
              // columns:data.columns,
              dataSource: data.dataSource,
              pageInfo: data.pageInfo,
            });
          },
        });
      },
    );
  };

  //控制模态框显示隐藏
  setVisible = (e) => {
    this.setState({
      visible: e,
    });
  };

  //跳转到交易对手详情
  InfoQuery = (item) => {
    if (isZiGuanEvir()) {
      //来自资管平台 则给iframe发送交易对手id 通知其跳转到详情的iframe
      const obj = { counterpartiesID: item, ziGuanKey: new Date().getTime() };
      window.parent.postMessage(obj, '*'); //抛出事件，将数据转成字符串避免一些浏览器不兼容
      return;
    }
    //maat环境 跳转方式
    sessionStorage.setItem('counterpartiesID', item);
    sessionStorage.setItem('isQueryUpdate', 1);
    this.props.dispatch(routerRedux.push(`/counterpartyManagement/counterpartyInfoQuery`));
    //用来促发model渲染接收数据
    this.props.dispatch({
      type: 'counterpartyInformationM/setState',
      payload: {
        id: item,
      },
    });
  };

  //点击新增
  handleTableSave = () => {
    this.setState({
      visible: true,
    });
  };

  //删除黑白名单
  onDeleteFrom = (item) => {
    const { dispatch } = this.props;
    const { type } = this.props;
    let that = this;
    let title = type == 'black' ? `是否从交易对手黑名单中删除“${item.shortName}”` : `是否从交易对手白名单中删除“${item.shortName}”`;

    dispatch({
      type: 'personnelManagement/deleteBWlist',
      payload: {
        id: item.id,
        portfolioId: item.portfolioId,
        type: type,
      },
      callback: (msg) => {
        if (msg) {
          that.getTableDataNew();
        }
      },
    });
  };

  //转value
  showValue = (text, statusEnum) => {
    if (!text) return '';
    let newDate = '';
    statusEnum.map((item) => {
      if (item.value == text) {
        newDate = item.title;
      }
    });
    return newDate;
  };

  //渲染表格
  renderTable = () => {
    const {
      personnelManagement: { statusEnum },
    } = this.props;
    const { columns, dataSource, pageInfo } = this.state;
    const { loading } = this.props;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};

    //表格增加排序
    columns.map((item, key) => {
      item.dataIndex = item.key;
      if (item.key == 'shortName' || item.key == 'longName' || item.key == 'creator') {
        item.sorter = true;
        item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
      }
      if (item.key == 'status') {
        item.render = (text, record) => {
          return <span> {this.showValue(text, statusEnum)}</span>;
        };
      }
      if (item.key == 'portfolioName') {
        item.render = (text, record) => {
          //找出产品组名称 原因是在资管，交易对手一个数据库，基础信息（包含用户信息、产品、组合、产品组等）一个库，两个库还不一样，所以数据没有共享
          return getProductName(record.portfolioId, this.state.productList) || '--';
        };
      }
    });

    //因为columns来自props，会不停的渲染添加操作列，在此做一下判断
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        key: 'operation',
        dataIndex: 'operation',
        title: '操作',
        width: '150px',
        type: 'operate',
        operates: [
          {
            title: '查看',
            onClick: (record, index) => this.InfoQuery(record.id),
          },
          {
            title: '删除',
            onClick: (record, index) => this.onDeleteFrom(record),
            rules: {
              disabled: { relation: 'and', items: [{ key: 'status', value: ['1'], relation: ['!='] }] },
            },
          },
        ],
      });
    }

    return (
      <div>
        <TableC
          columns={columns}
          dataSource={dataSource || []}
          onChange={this.handleTableChange3}
          current={this.state.currentPage}
          pageSize={this.state.numInPage}
          selfScrollY={true}
          loading={loading}
          total={pageInfo.total || 0}
          rowKey='key'
        />
      </div>
    );
  };

  render() {
    const {
      personnelManagement: { portfolioList, statusEnum, shortName },
    } = this.props;
    const { type } = this.props;
    const cardTitle = type && type == 'black' ? '交易对手黑名单管理' : '交易对手白名单管理';
    const modal = {
      titleModal: type && type == 'black' ? '交易对手黑名单新增' : '交易对手白名单新增',
      type: type,
      portfolioList,
      shortName,
    };
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioId',
          type: DATA_ENTRY.PRODUCTGROUP,
        },
        {
          dataIndex: 'shortName',
          title: '交易对手短名',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'longName',
          title: '交易对手长名',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'status',
          title: '可用状态',
          type: DATA_ENTRY.SELECT,
          isMultiple: true,
          dataSource: statusEnum,
        },
      ],
      onQuery: (e) => this.getTableData(e),
      onClear: (e) => this.onClear(e),
    };
    return (
      <ContentPackage
        title={cardTitle}
        contentHtml={
          <div>
            <div className={style.bondDeviation}>
              <Card bordered={false}>
                <AdvancedSearch {...searchProps} />
                <div style={{ marginTop: '13px' }}>
                  <PrimaryC onClick={this.handleTableSave} title='新增' />
                </div>
                <div style={{ marginTop: '13px' }}>{this.renderTable()}</div>
              </Card>
            </div>
            <ModalInst {...modal} visible={this.state.visible} setVisible={this.setVisible} getTableDataNew={this.getTableDataNew} />
          </div>
        }
      />
    );
  }
}
